/**
 * Copyright @2016-present, Sumscope, Inc.
 * All rights reserved.
 */

const isFunction = require('lodash/isFunction');
const Cookies = require('cookies');

module.exports = function (app, session) {
  return async(socket, next) => {
    let request = socket.request;
    let response = wrapResponse(socket.handshake);
    let ctx = {
      cookies: new Cookies(request, response, {
        keys: app.keys,
        secure: response.secure
      })
    };
    await session(ctx, next);
    return ctx.session;
  };
};

function wrapResponse(handshake) {
  if (!isFunction(handshake.getHeader)) {
    handshake.getHeader = function (key) {
      return this.header[key];
    }.bind(handshake);
  }
  if (!isFunction(handshake.setHeader)) {
    handshake.setHeader = function (key, value) {
      // ignore
    }.bind(handshake);
  }
  return handshake;
}
